package com.peng.ivos.dict.service.impl;

import com.peng.ivos.base.response.JsonResult;
import com.peng.ivos.base.response.PageData;
import com.peng.ivos.base.util.CacheUtils;
import com.peng.ivos.dict.mapper.DictMapper;
import com.peng.ivos.dict.pojo.dto.DictQuery;
import com.peng.ivos.dict.pojo.dto.DictSaveParam;
import com.peng.ivos.dict.pojo.entity.Dict;
import com.peng.ivos.dict.pojo.vo.DictVO;
import com.peng.ivos.dict.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 字典业务层实现类
 * @author： Peng
 * @date： 2024/5/27
 * @version: 1.0
 */
@Service
@Slf4j
public class DictServiceImpl implements DictService {
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private CacheUtils cacheUtils;

    @Override
    public PageData getDictByExample(DictQuery dictQuery) {
        // 查询字典列表
        List<DictVO> dictVOList = dictMapper.selectDictByExample(dictQuery);
        //准备PageData对象用于装返回前端的数据
        PageData dictData = new PageData();
        dictData.setList(dictVOList);
        dictData.setTotal(dictMapper.countDict(dictQuery));
        return dictData;
    }

    @Override
    public JsonResult saveDict(DictSaveParam dictSaveParam) {
        Dict dict = Dict.builder()
                .name(dictSaveParam.getName())
                .code(dictSaveParam.getCode())
                .remark(dictSaveParam.getRemark())
                .createTime(new Date())
                .build();
        if (dictSaveParam.getId() != null){
            dict.setId(dictSaveParam.getId());
            return dictMapper.updateDict(dict)>0 ? JsonResult.success("字典更新成功") : JsonResult.error("字典更新失败");
        }
        return dictMapper.insertDict(dict)>0 ? JsonResult.success("字典新增成功") : JsonResult.error("字典新增失败");
    }

    @Override
    public JsonResult deleteDict(Long id) {
        //同时清空redis中与该字典相关的缓存数据
        DictQuery dictQuery=new DictQuery();
        dictQuery.setId(id);
        List<DictVO> dictVOList=dictMapper.selectDictByExample(dictQuery);
        if(dictVOList!=null && dictVOList.size()>0){
            DictVO dictVO = dictVOList.get(0);
            //根据dict的code删除之前的redis缓存
            cacheUtils.delete("dictOption"+dictVO.getCode());
        }
        return dictMapper.deleteDictById(id)>0 ? JsonResult.success("字典删除成功") : JsonResult.error("字典删除失败");
    }
}
